import React, { PureComponent, Fragment } from 'react';
import { Card, Row, Col } from 'antd';
import ReactDOM from 'react-dom';
// 插件
import moment from 'moment';

// 组件
import YhglQueyFm from './components/Yhgl/YhglQueyForm';

import YhglTable from './components/Yhgl/YhglTable';
import YhglMap from './components/Yhgl/YhglMap';
import PointPopup from './components/Yhgl/PointPopup';

import { getAuthority } from '@/utils/authority';
import RenderAuthorized from '@/components/Authorized';
import { connect } from 'dva';
// 样式
import styles from './Yhgl.less';

const Authorized = RenderAuthorized(getAuthority());

const icon_0 = new L.divIcon({
  iconSize: [20, 20],
  html: `<div><image class="pointIcon" src='${require(`@/assets/images/pointIcon/公用设施.png`)}'/></div>`,
});
const icon_1 = new L.divIcon({
  iconSize: [20, 20],
  html: `<div><image class="pointIcon" src='${require(`@/assets/images/pointIcon/市容环境.png`)}'/></div>`,
});
const icon_2 = new L.divIcon({
  iconSize: [20, 20],
  html: `<div><image class="pointIcon" src='${require(`@/assets/images/pointIcon/桥梁设施.png`)}'/></div>`,
});
const icon_3 = new L.divIcon({
  iconSize: [20, 20],
  html: `<div><image class="pointIcon" src='${require(`@/assets/images/pointIcon/百日专项.png`)}'/></div>`,
});
const icon_4 = new L.divIcon({
  iconSize: [20, 20],
  html: `<div><image class="pointIcon" src='${require(`@/assets/images/pointIcon/突发事件.png`)}'/></div>`,
});
const icon_5 = new L.divIcon({
  iconSize: [20, 20],
  html: `<div><image class="pointIcon" src='${require(`@/assets/images/pointIcon/道路交通.png`)}'/></div>`,
});
const icon_6 = new L.divIcon({
  iconSize: [20, 20],
  html: `<div><image class="pointIcon" src='${require(`@/assets/images/pointIcon/公用设施.png`)}'/></div>`,
});
const icon_7 = new L.divIcon({
  iconSize: [20, 20],
  html: `<div><image class="pointIcon" src='${require(`@/assets/images/pointIcon/公用设施.png`)}'/></div>`,
});
const icon_8 = new L.divIcon({
  iconSize: [20, 20],
  html: `<div><image class="pointIcon" src='${require(`@/assets/images/pointIcon/公用设施.png`)}'/></div>`,
});

@connect(({ maintain, config, loading, global }) => ({
  yhdwList: maintain.yhdwList,
  sblyList: maintain.sblyList,
  yhglTbData: maintain.yhglTb.data ? maintain.yhglTb.data : [],
  yhglTbTotal: maintain.yhglTb.total,
  loading: loading.effects['maintain/fetchGetQueryProblem'],
  wtlxList: maintain.wtlxList,
  currentUrl: global.currentUrl,
}))
class Yhgl extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      total: 0,
    };
    this.dispatch = this.props.dispatch;

    this.handleGetMap = this.handleGetMap.bind(this);
    this.clickItem = this.clickItem.bind(this);

    this.user_id = sessionStorage.getItem('user_id');
  }
  componentWillMount() {
    const { dispatch, match } = this.props;
    dispatch({ type: 'global/fetchUrl', payload: match.url });
  }
  componentDidMount() {
    var refs = this.refs;
    var cThis = this;
    var mapDom = this.map;

    //点位layer
    cThis.pointsLayer = L.geoJSON().addTo(mapDom);
    cThis.pointsLayerClear = function() {
      this.pointsLayer.clearLayers();
    };

    mapDom.createPane('invisibleLayer');
    mapDom.getPane('invisibleLayer').style.zIndex = 400;

    //map上加点
    cThis.addPointsToMap = function(data, parentlayer, area, prefix) {
      for (var i = 0; i < data.length; i++) {
        var p = data[i];
        var g = L.geoJSON(
          {
            type: 'Point',
            coordinates: [p.x, p.y],
          },
          {
            pointToLayer: function(feature, latlng) {
              var icon = icon_0;
              switch (p.cname) {
                case '公用设施':
                  icon = icon_0;
                  break;
                case '市容环境':
                  icon = icon_1;
                  break;
                case '桥梁设施':
                  icon = icon_2;
                  break;
                case '百日专项':
                  icon = icon_3;
                  break;
                case '突发事件':
                  icon = icon_4;
                  break;
                case '道路交通':
                  icon = icon_5;
                  break;
                // case '车行道':
                //   icon = icon_0;
                //   break;
                // case '人行道':
                //   icon = icon_4;
                //   break;
                default:
                  break;
              }
              return L.marker(latlng, { icon: icon });
            },
            style: function(feature) {},
          }
        );
        g.pointId = p.id;
        g.bindPopup(
          (function(p) {
            return function() {
              //跳出弹窗
              var popup = document.createElement('div');
              ReactDOM.render(<PointPopup data={p} />, popup);
              return popup;
            };
          })(p),
          {
            className: 'leafletPointPopup',
            maxWidth: 800,
            offset: [8, 0],
          }
        );
        //固定label
        // var label = p.Name + '(' + pointGroup[p.Type] + ')';
        // console.log(label);
        // g.bindTooltip(label, {
        //   permanent: true,
        //   offset: [0, 5],
        //   direction: 'top',
        //   className: 'pointTooltip',
        // });

        g.addTo(parentlayer);
        this.map.setView(parentlayer.getBounds().getCenter(), 12);
      }
    };

    this.GetCompany({ type: '养护维修' });
    this.GetQueryProblem();
    this.ReportSource();
  }

  // 养护管理-查询
  GetQueryProblem = ({
    app = 1,
    pagesize = 10,
    pageindex = 1,
    companyid = null,
    type = null,
    ztype = null,
    source = null,
    status = null,
    bovertime = null,
    eovertime = null,
    btime = null,
    etime = null,
  } = {}) => {
    this.dispatch({
      type: 'maintain/fetchGetQueryProblem',
      payload: {
        app: app,
        pagesize: pagesize,
        pageindex: pageindex,
        companyid: companyid,
        type: type,
        ztype: ztype,
        ztype: ztype,
        source: source,
        status: status,
        bovertime: bovertime,
        eovertime: eovertime,
        btime: btime,
        etime: etime,
      },
      callback: response => {
        if (response.ErrorMessage) {
          message.error.error('获取失败');
          console.log(response.ErrorMessage);
        }
        //保存查询条件
        var queryCon = {};
        queryCon['app'] = app;
        queryCon['pagesize'] = pagesize;
        queryCon['pageindex'] = pageindex;
        queryCon['companyid'] = companyid;
        queryCon['type'] = type;
        queryCon['source'] = source;
        queryCon['status'] = status;
        queryCon['bovertime'] = bovertime;
        queryCon['eovertime'] = eovertime;
        queryCon['btime'] = btime;
        queryCon['etime'] = etime;
        this.setState({
          queryCon: queryCon,
        });
        this.pointsLayerClear();
        this.addPointsToMap(response.data, this.pointsLayer);
      },
    });
  };

  // 获取"养护单位"
  GetCompany = ({ type = null } = {}) => {
    this.dispatch({
      type: 'maintain/fetchGetCompany',
      payload: {
        type: type,
      },
      callback: response => {
        if (response.ErrorMessage) {
          message.error.error('获取失败');
          console.log(response.ErrorMessage);
        }
      },
    });
  };

  // 获取"问题类型" 大类
  GetClass = () => {
    this.dispatch({
      type: 'maintain/fetchGetClass',
      callback: response => {
        if (response.ErrorMessage) {
          message.error.error('获取失败');
          console.log(response.ErrorMessage);
        }
      },
    });
  };

  // 获取上报来源
  ReportSource = () => {
    this.dispatch({
      type: 'maintain/fetchReportSource',
      callback: response => {
        if (response.ErrorMessage) {
          message.error.error('获取失败');
          console.log(response.ErrorMessage);
        }
      },
    });
  };

  handleGetMap = e => {
    this.map = e;
  };

  //单击item
  clickItem(item) {
    var cLayer = this.pointsLayer;
    var m = this.refs.map;
    cLayer.eachLayer(function(l) {
      if (item.id == l.pointId) {
        l.openPopup();
        m.map.fitBounds(l.getBounds(), { maxZoom: 16 });
      }
    });
  }

  //权限
  getAuth = () => {
    const { dispatch, currentUrl } = this.props;
    dispatch({
      type: 'global/fetchAuthorityElements',
      payload: { url: currentUrl },
    });
  };

  // 功能接口
  // 根据查询条件渲染表格

  render() {
    var s = this.state;
    const { yhdwList, yhglTbData, yhglTbTotal, wtlxList, sblyList } = this.props;
    return (
      <Fragment>
        <Card style={{ margin: '10px' }} bodyStyle={{ padding: 10 }}>
          <YhglQueyFm
            ref="queryFm"
            parent={this}
            yhdwList={yhdwList}
            GetQueryProblem={this.GetQueryProblem}
            queryCon={s.queryCon}
            sblyList={sblyList}
          />
        </Card>
        <Row>
          <Col span={14}>
            <Card
              title={
                <span style={{ borderLeft: '4px solid #3CB371', paddingLeft: '10px' }}>
                  基本信息表
                </span>
              }
              className={styles.tableCard}
              style={{ margin: '10px 5px 10px 10px' }}
            >
              <YhglTable
                yhglTbData={yhglTbData}
                yhdwList={yhdwList}
                GetQueryProblem={this.GetQueryProblem}
                clickItem={this.clickItem}
                queryCon={s.queryCon}
                yhglTbTotal={yhglTbTotal}
                wtlxList={wtlxList}
                sblyList={sblyList}
              />
            </Card>
          </Col>
          <Col span={10}>
            <Card
              title={
                <span style={{ borderLeft: '4px solid #3CB371', paddingLeft: '10px' }}>
                  地图定位
                </span>
              }
              className={styles.mapCard}
              style={{ margin: '10px 10px 10px 5px', padding: 0 }}
            >
              <YhglMap ref="map" GetMap={this.handleGetMap} />
            </Card>
          </Col>
        </Row>
      </Fragment>
    );
  }
}

export default Yhgl;
